import Access from '@/components/Access';
import Menu from '@/components/Form/Menu';
import HandleBtn from '@/components/HandleBar/btn';
import type { ActionType, ProColumns, ProFormInstance } from '@/components/Pro/';
import { ModalForm, ProFormText, ProFormTextArea, ProTable } from '@/components/Pro/';
import Tabs from '@/components/Tabs';
import {
  sysRoleControllerAddRole as add,
  sysRoleControllerBatch as batchHandle,
  sysRoleControllerDownloadExcel as downloadFile,
  sysRoleControllerEditRole as edit,
  sysRoleControllerGetRoleMenus,
  sysRoleControllerList as getList,
  sysRoleControllerNextRoleNo,
  sysRoleControllerSaveRoleMenus as saveRoleMenus,
  sysRoleControllerSaveRoleStatus,
  sysRoleControllerUploadExcel as uploadFile,
} from '@/services/ess/sysRole';
import {
  DATABASE_TYPE_ENUM,
  fetchDictInfo,
  getGlobalHandleTip,
  GLOBAL_HANDLE_TIP_TYPE,
} from '@/utils';
import { getMenuList } from '@/utils/';
import { downloadFetch } from '@/utils/downloadFile';
import type { UploadProps } from 'antd';
import { Flex, Form, message, Modal, Space, Switch, Upload } from 'antd';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useAccess, useIntl } from 'umi';
import Styles from './index.less';

const { confirm } = Modal;

/**
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.SysRoleReq) => {
  try {
    let result = await add({
      ...fields,
    });
    if (result.success) {
      getGlobalHandleTip(GLOBAL_HANDLE_TIP_TYPE.ADD);
      return true;
    }
    return false;
  } catch (error) {
    getGlobalHandleTip(GLOBAL_HANDLE_TIP_TYPE.ADD, {
      error: true,
    });
    return false;
  }
};

/**
 * @zh-CN 编辑节点
 * @param fields
 */
const handleEdit = async (fields: API.SysRoleReq) => {
  try {
    let result = await edit({
      ...fields,
    });
    if (result.success) {
      getGlobalHandleTip(GLOBAL_HANDLE_TIP_TYPE.EDIT);
      return true;
    }
    return false;
  } catch (error) {
    getGlobalHandleTip(GLOBAL_HANDLE_TIP_TYPE.EDIT, {
      error: true,
    });
    return false;
  }
};

const TableList: React.FC = () => {
  console.log('Component rendering');

  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const [menuModalOpen, handleMenuModalOpen] = useState<boolean>(false);
  const formRef = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.SysRole>({});
  const [selectedRowsState, setSelectedRows] = useState<API.SysRole[]>([]);
  const [dataSource, setDataSource] = useState<API.SysRole[]>([]);
  const [disabled, setDisabled] = useState(false);
  // const [menuData, setMenuData] = useState([]);
  const access = useAccess();
  const intl = useIntl();
  const [platformType, setPlatformType] = useState<'WEB' | 'APP'>('WEB');
  const [webMenuData, setWebMenuData] = useState([]);
  const [appMenuData, setAppMenuData] = useState([]);
  const [webSelectedIds, setWebSelectedIds] = useState<string[]>([]);
  const [appSelectedIds, setAppSelectedIds] = useState<string[]>([]);
  const [menuCache, setMenuCache] = useState<{
    web: string[];
    app: string[];
  }>({ web: [], app: [] });

  // 只在组件挂载时获取菜单数据
  useEffect(() => {
    console.log('Fetching menu data...');
    const fetchMenuData = async () => {
      try {
        const webData = await getMenuList(sysRoleControllerGetRoleMenus, { platformType: 'WEB' });
        const appData = await getMenuList(sysRoleControllerGetRoleMenus, { platformType: 'APP' });
        setWebMenuData(webData);
        setAppMenuData(appData);
      } catch (error) {
        console.error('Error fetching menu data:', error);
      }
    };
    fetchMenuData();
  }, []); // 空依赖数组

  // 1. 修改初始化逻辑
  useEffect(() => {
    if (currentRow?.menuIds) {
      const fetchMenuDetails = async () => {
        try {
          const [webResult, appResult] = await Promise.all([
            sysRoleControllerGetRoleMenus({ platformType: 'WEB' }),
            sysRoleControllerGetRoleMenus({ platformType: 'APP' }),
          ]);

          const currentMenuIds = currentRow.menuIds.map((id) => String(id));

          // 根据菜单类型过滤
          const webSelected = currentMenuIds.filter((id) =>
            webResult.data.some((menu) => String(menu.id) === id),
          );
          const appSelected = currentMenuIds.filter((id) =>
            appResult.data.some((menu) => String(menu.id) === id),
          );

          setWebSelectedIds(webSelected);
          setAppSelectedIds(appSelected);
        } catch (error) {
          console.error('Error fetching menu details:', error);
        }
      };

      fetchMenuDetails();
    }
  }, [currentRow?.menuIds]);

  // 改变状态后重置selectedRowsState数据
  useEffect(() => {
    if (!selectedRowsState.length) {
      return;
    }
    const newSelectedRows = selectedRowsState.map((row) => {
      const newRow = dataSource.find((item) => row.id === item.id);
      if (newRow) {
        return newRow;
      }
      return row;
    });
    setSelectedRows(newSelectedRows);
  }, [dataSource]);

  function handleBatch(type: string, row = selectedRowsState) {
    if (row.length < 1) {
      message.warning(intl.formatMessage({ id: 'global.leastOne' }));
      return;
    }

    if (disabled) return;
    setDisabled(true);

    confirm({
      title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
      content:
        type === 'DELETE'
          ? intl.formatMessage({
              id: 'systemManagement.supplementary.dataCannotBeRestoredAfterDeletion',
            })
          : intl.formatMessage({
              id: 'systemManagement.supplementary.doYouWantToChangeTheEnabledStatusOfThisData',
            }),
      onOk: async () => {
        const res = await batchHandle({
          ids: row.map((row) => row.id),
          type,
        });
        if (res.success) {
          const handleType =
            (type === 'DELETE' && GLOBAL_HANDLE_TIP_TYPE.DEL) ||
            (type === 'OPEN' && GLOBAL_HANDLE_TIP_TYPE.ENABLE) ||
            (type === 'DISABLE' && GLOBAL_HANDLE_TIP_TYPE.DISABLED) ||
            undefined;
          getGlobalHandleTip(handleType);
          actionRef.current?.reloadAndRest?.();
        }
      },
      afterClose: () => {
        setDisabled(false);
      },
    });
  }

  const handleSwitchStatus = (switchVal: boolean, record: API.SysRole) => {
    confirm({
      title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
      content: intl.formatMessage({
        id: 'systemManagement.supplementary.doYouWantToChangeTheEnabledStatusOfThisData',
      }),
      onOk: async () => {
        let status = switchVal ? '1' : '0';
        const params: API.sysRoleControllerSaveRoleStatusParams = {
          id: record.id,
          status: status,
        } as any;
        const res = await sysRoleControllerSaveRoleStatus(params);
        if (res) {
          getGlobalHandleTip(GLOBAL_HANDLE_TIP_TYPE.ENABLE);
          actionRef?.current?.reloadAndRest?.();
        }
      },
    });
  };

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: true,
    showUploadList: false,
    customRequest: async (info) => {
      const form = new FormData();
      form.append('file', info.file);
      const res = await uploadFile(form, { ingoreErrorMsg: true });
      if (res?.success) {
        message.success(
          `${info.file.name} ${intl.formatMessage({
            id: 'systemManagement.neddTochange.fileImportSuccess',
          })}`,
        );
        actionRef?.current?.reloadAndRest?.();
        return;
      }
      const msg = res?.message;
      message.error(
        `${info.file.name} ${intl.formatMessage({
          id: 'systemManagement.neddTochange.fileImportFailed',
        })} ${msg ? ',' + msg : ''}`,
      );
    },
  };

  const columns: ProColumns<API.SysRole>[] = [
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.SN' }),
      hideInSearch: true,
      dataIndex: 'pageIndex',
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.roleManagementMenu.roleName' }),
      dataIndex: 'roleName',
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.roleManagementMenu.characterStatus' }),
      dataIndex: 'status',
      request: () => fetchDictInfo(DATABASE_TYPE_ENUM.ROLE_STATUS),
      render: (_, record) => (
        <Switch
          checkedChildren={intl.formatMessage({ id: 'systemManagement.generalProcedure.enable' })}
          unCheckedChildren={intl.formatMessage({
            id: 'systemManagement.generalProcedure.disable',
          })}
          checked={Boolean(record.status)}
          onChange={(checked) => {
            handleSwitchStatus(checked, record);
          }}
        />
      ),
      hideInTable: !access.can('sys:role:setStatus'),
      hideInSearch: !access.can('sys:role:setStatus'),
    },

    {
      title: intl.formatMessage({ id: 'systemManagement.roleManagementMenu.roleCoding' }),
      dataIndex: 'roleNo',
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.roleManagementMenu.creationTime' }),
      dataIndex: 'createTime',
      valueType: 'dateRange',
      width: 160,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
      render: (_, record) => record.createTime,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.roleManagementMenu.modificationTime' }),
      dataIndex: 'modifyTime',
      hideInSearch: true,
      width: 160,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.operation' }),
      dataIndex: 'option',
      valueType: 'option',
      width: 160,
      render: (_, record) => [
        <Space key="space">
          <Access accessible={access['sys:role:menu']} key="menu">
            <a
              key="menu"
              onClick={() => {
                handleMenuModalOpen(true);
                setCurrentRow(record);
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.menuPermissions' })}
            </a>
          </Access>

          <Access accessible={access['sys:role:edit']} key="edit">
            <a
              key="edit"
              onClick={() => {
                handleModalOpen(true);
                setCurrentRow(record);
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })}
            </a>
          </Access>
          <Access accessible={access['sys:role:del']} key="del">
            <a
              key="delete"
              className="global-del-color"
              onClick={() => {
                handleBatch('DELETE', [record]);
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.delete' })}
            </a>
          </Access>
        </Space>,
      ],
    },
  ];
  const isEnglish = useIntl().locale === 'en-US';
  // 使用 useMemo 缓存菜单表单项
  const menuFormItem = useMemo(() => {
    const formItemProps = {
      style: { flex: 1 },
      labelCol: { span: isEnglish ? 5 : 4 },
      label: intl.formatMessage({ id: 'systemManagement.menuManagementMenu.selectMenu' }),
    };

    const currentValue = platformType === 'WEB' ? webSelectedIds : appSelectedIds;
    const currentMenuData = platformType === 'WEB' ? webMenuData : appMenuData;

    return (
      <Form.Item
        {...formItemProps}
        name={platformType === 'WEB' ? 'webMenuIds' : 'appMenuIds'}
        initialValue={currentValue}
        rules={[
          {
            required: platformType === 'WEB',
            message: intl.formatMessage({
              id: 'systemManagement.menuManagementMenu.meunRequire',
            }),
          },
        ]}
      >
        <Menu
          treeData={currentMenuData}
          value={currentValue}
          onChange={(ids) => {
            console.log('Menu onChange:', {
              platformType,
              ids,
              currentValue,
              menuCache,
            });

            const newCache =
              platformType === 'WEB' ? { ...menuCache, web: ids } : { ...menuCache, app: ids };

            // 同时更新选中状态和缓存
            if (platformType === 'WEB') {
              setWebSelectedIds(ids);
            } else {
              setAppSelectedIds(ids);
            }
            setMenuCache(newCache);
          }}
        />
      </Form.Item>
    );
  }, [
    platformType,
    webMenuData,
    appMenuData,
    webSelectedIds,
    appSelectedIds,
    menuCache,
    intl,
    isEnglish,
  ]);

  // 3. 修改 tab 切换逻辑
  useEffect(() => {
    console.log('Tab 切换:', {
      platformType,
      menuCache,
      webSelectedIds,
      appSelectedIds,
    });

    // 切换 tab 时，从缓存中恢复状态
    if (platformType === 'WEB') {
      setWebSelectedIds(menuCache.web);
    } else {
      setAppSelectedIds(menuCache.app);
    }
  }, [platformType, menuCache]);

  // 4. 修改提交逻辑
  const handleMenuSubmit = async () => {
    try {
      // 使用 menuCache 来检查 WEB 端菜单选择状态
      if (!menuCache.web.length) {
        message.warning(
          intl.formatMessage({
            id: 'systemManagement.menuManagementMenu.webMenuRequired',
          }),
        );
        // 切换到 WEB tab
        setPlatformType('WEB');
        return false;
      }

      // 合并菜单 ID，使用 menuCache 中的数据
      const allMenuIds = [...new Set([...menuCache.web, ...menuCache.app])];

      console.log('提交菜单权限:', {
        webMenuIds: menuCache.web,
        appMenuIds: menuCache.app,
        allMenuIds,
      });

      const success = await saveRoleMenus({
        roleId: currentRow.id,
        menuIds: allMenuIds,
      } as API.SysRoleMenuReq);

      if (success) {
        message.success(
          intl.formatMessage({ id: 'systemManagement.requiredFields.menuEditSuccess' }),
        );
        handleMenuModalOpen(false);
        if (actionRef.current) {
          actionRef.current.reload();
        }
        return true;
      }
      return false;
    } catch (error) {
      console.error('Error saving role menus:', error);
      return false;
    }
  };

  return (
    <div>
      <ProTable<API.SysRole, API.PageParams>
        className={'global-primary-table'}
        headerTitle={intl.formatMessage({
          id: 'systemManagement.roleManagementMenu.roleManagement',
        })}
        actionRef={actionRef}
        formRef={formRef}
        rowKey="id"
        toolBarRender={() => [
          <Access accessible={access['sys:role:add']} key="add">
            <HandleBtn
              handleType="add"
              onClick={() => {
                setCurrentRow({});
                handleModalOpen(true);
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.new' })}
            </HandleBtn>
          </Access>,
          <Access accessible={access['sys:role:import']} key="import">
            <Upload {...uploadProps}>
              <HandleBtn handleType="import">
                {intl.formatMessage({ id: 'systemManagement.generalProcedure.import' })}
              </HandleBtn>
            </Upload>
          </Access>,
          <Access accessible={access['sys:role:export']} key="export">
            <HandleBtn
              handleType="export"
              onClick={() => downloadFetch(downloadFile, formRef?.current?.getFieldsFormatValue())}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.export' })}
            </HandleBtn>
          </Access>,
          <Access accessible={access['sys:role:setStatus']} key="enable">
            <HandleBtn handleType="enable" key="enable" onClick={() => handleBatch('OPEN')}>
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.batchEnable' })}
            </HandleBtn>
          </Access>,
          <Access accessible={access['sys:role:setStatus']} key="disabled">
            <HandleBtn handleType="disabled" key="disabled" onClick={() => handleBatch('DISABLE')}>
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.batchDisable' })}
            </HandleBtn>
          </Access>,
          <Access accessible={access['sys:role:del']} key="del">
            <HandleBtn
              onClick={() => {
                handleBatch('DELETE');
              }}
              handleType="delete"
              key="delete"
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.batchDelete' })}
            </HandleBtn>
          </Access>,
        ]}
        request={async (params) => {
          const result = await getList(params);
          setDataSource(result?.data?.records);
          return result;
        }}
        dataSource={dataSource}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      <ModalForm
        modalProps={{
          destroyOnClose: true,
        }}
        title={
          currentRow?.id
            ? intl.formatMessage({ id: 'systemManagement.roleManagementMenu.editRole' })
            : intl.formatMessage({ id: 'systemManagement.roleManagementMenu.addRole' })
        }
        initialValues={{ ...currentRow }}
        width="530px"
        labelCol={{
          flex: `0 0 100px`,
        }}
        style={{
          marginRight: 50,
        }}
        request={
          !currentRow?.id &&
          (async () => {
            const res = await sysRoleControllerNextRoleNo();
            return { roleNo: res?.data };
          })
        }
        colProps={{ md: 12 }}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          console.log(value, '我是完成后的值');
          let success;
          if (currentRow?.id) {
            success = await handleEdit({ ...currentRow, ...value } as API.SysRoleReq);
          } else {
            success = await handleAdd(value as API.SysRoleReq);
          }
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          name="roleNo"
          colProps={{ md: 24 }}
          label={intl.formatMessage({ id: 'systemManagement.roleManagementMenu.roleCoding' })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.roleCode' }),
            },
            {
              max: 10,
              message: intl.formatMessage({ id: 'systemManagement.neddTochange.maxTenDigits' }),
            },
          ]}
        />
        <ProFormText
          name="roleName"
          colProps={{ md: 24 }}
          label={intl.formatMessage({ id: 'systemManagement.roleManagementMenu.roleName' })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.roleName' }),
            },
          ]}
        />
        <ProFormTextArea
          colProps={{ md: 24 }}
          label={intl.formatMessage({
            id: 'systemManagement.roleManagementMenu.remarksDescription',
          })}
          name="remark"
        />
      </ModalForm>
      <ModalForm
        modalProps={{
          destroyOnClose: true,
        }}
        title={intl.formatMessage({ id: 'systemManagement.generalProcedure.menuPermissions' })}
        initialValues={{
          ...currentRow,
          webMenuIds: currentRow.menuIds,
          appMenuIds: currentRow.menuIds,
        }}
        width="600px"
        labelCol={{
          flex: `0 0 100px`,
        }}
        style={{
          marginRight: 30,
        }}
        open={menuModalOpen}
        onOpenChange={handleMenuModalOpen}
        onFinish={handleMenuSubmit}
      >
        <Tabs
          activeKey={platformType}
          onChange={(key) => {
            setPlatformType(key as 'WEB' | 'APP');
          }}
          className={Styles.smallTabs}
          items={[
            {
              key: 'WEB',
              label: intl.formatMessage({
                id: 'systemManagement.menuManagementMenu.WEBPermissions',
              }),
            },
            {
              key: 'APP',
              label: intl.formatMessage({
                id: 'systemManagement.menuManagementMenu.APPPermissions',
              }),
            },
          ]}
        />
        <Flex style={{ width: '100%', marginInline: 4 }}>{menuFormItem}</Flex>
      </ModalForm>
    </div>
  );
};
export default TableList;
